package com.hnichr.ump.plan.service.impl;

import com.hnichr.ump.common.plan.entity.PlanGroupUser;
import com.hnichr.ump.common.plan.service.PlanGroupUserService;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.security.entity.User;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.Set;

@Service
public class PlanGroupUserServiceImpl extends BaseServiceImpl<PlanGroupUser> implements PlanGroupUserService {
    @Transactional(readOnly = true)
    @Override
    public List<PlanGroupUser> listByGroupId(String groupId){
        return JpaUtil.linq(PlanGroupUser.class).equal("groupId",groupId).list();
    }

    @Transactional(readOnly = true)
    @Override
    public Page<PlanGroupUser> pageByGroupId(String groupId, Pageable page){
        return JpaUtil.linq(PlanGroupUser.class).equal("groupId",groupId).paging(page);
    }

    @Transactional
    @Override
    public List<PlanGroupUser> add(List<PlanGroupUser> planGroupUsers){
        Set<String> userNames = planGroupUsers.stream().map(PlanGroupUser::getUsername).collect(Collectors.toSet());
        List<PlanGroupUser> existsLs =JpaUtil.linq(PlanGroupUser.class).in("username",userNames).list();
        if(CollectionUtils.isNotEmpty(existsLs)){
            throw new RuntimeException("用户"+existsLs.get(0).getUsername()+"已存在");
        }
        List<User> userLs =JpaUtil.linq(User.class).in("username",userNames).list();
        Map<String,User> userMap = JpaUtil.index(userLs,"username");

        for(PlanGroupUser groupUser:planGroupUsers){
            if(!userMap.containsKey(groupUser.getUsername())){
                continue;
            }
            groupUser.setNickname(userMap.get(groupUser.getUsername()).getNickname());
            this.save(groupUser);
        }
        return planGroupUsers;
    }

    @Transactional
    @Override
    public void remove(String ids){
        String [] ida = StringUtils.split(ids,",");
        for(String key:ida){
            PlanGroupUser groupUser = JpaUtil.getOne(PlanGroupUser.class,key);
            JpaUtil.remove(groupUser);
        }
    }
}
